package java6681.nio2;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.stream.Stream;

/**
 * @author DavidChen
 */
public class NIO2Dir6681Controller {

    @FXML
    private TextField tfDir;

    @FXML
    private Label lblCount;

    @FXML
    private TableView<MyFile6681> tableFiles;

    @FXML
    private TableColumn<MyFile6681, String> colName;

    @FXML
    private TableColumn<MyFile6681, String> colTime;

    @FXML
    private TableColumn<MyFile6681, String> colType;

    @FXML
    private TableColumn<MyFile6681, String> colSize;

    private final ObservableList<MyFile6681> FILELIST = FXCollections.observableArrayList();

    /** 当前所在目录的文件数量 */
    private Integer fileCount = 0;

    /** 当前所在目录的目录数量 */
    private Integer direcCount = 0;

    /** 用于保存当前所在的真实路径，实时获取输入框的值不靠谱 */
    private String realPath = "";

    @FXML
    void initialize(){
        tableFiles.setItems(FILELIST);
        colName.setCellValueFactory(new PropertyValueFactory<>("name"));
        colTime.setCellValueFactory(new PropertyValueFactory<>("modifiedTime"));
        colType.setCellValueFactory(new PropertyValueFactory<>("type"));
        colSize.setCellValueFactory(new PropertyValueFactory<>("size"));
    }

    @FXML
    void doubleClick(MouseEvent event) {
        MyFile6681 selectedItem = tableFiles.getSelectionModel().getSelectedItem();
        int selectIndex = tableFiles.getSelectionModel().getSelectedIndex();
        // 如果不是点击的标题栏，且为双击，且目标类型是文件夹，则执行目录更新操作
        if (selectIndex >= 0 && event.getClickCount() == 2 && "文件夹".equals(selectedItem.getType())){
            realPath = realPath + "\\" + selectedItem.getName();
            drawTableView(realPath);
            tfDir.setText(realPath);
        }
    }

    @FXML
    void listAll(ActionEvent event) {
        realPath = tfDir.getText().trim();
        drawTableView(realPath);
    }

    void drawTableView(String dir){
        // 如果输入为空，则默认显示当前目录
        Path path = Paths.get(dir);
        // 如果路径为空时，也就是默认目录时，把realPath设置为.方便切换到下级目录
        if("".equals(path.toString())){realPath = ".";}
        // 如果路径不存在，则进行提示并且显示默认目录
        if(!Files.exists(path)){ showAlert("指定目录不存在，已显示默认目录!");path = Paths.get(".");realPath = "."; }
        try {
            Stream<Path> list = Files.list(path);
            // 如果目录不存在，则files为null，就进行提示
            FILELIST.clear();fileCount = 0;direcCount = 0;
            list.forEach(item -> {
                try {
                    String type = Files.isRegularFile(item) ? "文件" : "文件夹";
                    String size = Files.isRegularFile(item) ? formatSize(Files.size(item)) : "";
                    FILELIST.add(new MyFile6681(item.getFileName().toString(), size, formatTime(Files.getLastModifiedTime(item)), type));
                } catch (IOException e) {
                    showAlert("指定目标不存在!");return;
                }
                if(Files.isRegularFile(item)){ fileCount++; }else{ direcCount++; }
            });
            lblCount.setText("子目录: " + direcCount + ", 文件: " + fileCount);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String formatSize(long size){
        long longSize = Math.round((float) size / 1024);
        if(longSize >= 1024){
            return Math.round((float) longSize / 1024) + "MB";
        }else{
            return longSize + "KB";
        }
    }

    String formatTime(FileTime time){
        LocalDateTime dateTime = LocalDateTime.ofInstant(time.toInstant(), ZoneId.systemDefault());
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"));
    }

    void showAlert(String text){
        new Alert(Alert.AlertType.WARNING, text, ButtonType.CLOSE).show();
    }

}